package wang.chunfan.springcloud.learning.hystrix.server.controller;

import cn.hutool.core.thread.ThreadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import wang.chunfan.springcloud.learning.hystrix.server.service.UserService;
import wang.chunfan.springcloud.learning.hystrix.server.model.Result;
import wang.chunfan.springcloud.learning.hystrix.server.model.User;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @version 1.0
 * @Author wangchunfan
 * @Date 2020/5/23 9:17
 **/
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    /**
     * 测试没有服务降级
     */
    @GetMapping("/testNoFallback/{id}")
    public Result testNoFallback(@PathVariable Long id) {
        return userService.testNoFallback(id);
    }

    /**
     * 测试服务降级
     */
    @GetMapping("/testFallback/{id}")
    public Result testFallback(@PathVariable Long id) {
        return userService.testFallback(id);
    }

    /**
     * 测试忽略异常降级
     */
    @GetMapping("/testIgnoreException/{id}")
    public Result testIgnoreException(@PathVariable Long id) {
        return userService.testIgnoreException(id);
    }

    /**
     * 测试请求缓存
     */
    @GetMapping("/testCache/{id}")
    public Result testCache(@PathVariable Long id) {
        userService.testCache(id);
        userService.testCache(id);
        return userService.testCache(id);
    }

    @GetMapping("/testRemoveCache/{id}")
    public Result testRemoveCache(@PathVariable Long id) {
        userService.testCache(id);
        userService.testCache(id);
        userService.cacheRemove(id);
        return userService.testCache(id);
    }

    @GetMapping("/testCollapser")
    public Result testCollapser() throws ExecutionException, InterruptedException {
        Future<User> future1 = userService.getUserFuture(3L);
        Future<User> future2 = userService.getUserFuture(4L);
        future1.get();
        future2.get();

        ThreadUtil.safeSleep(200);

        Future<User> future3 = userService.getUserFuture(5L);
        future3.get();
        return new Result();
    }
}
